/**
 * @fileoverview Load images as Surfaces.
 */

var CACHE = {};
/**
 * need to export preloading status for require
 * @ignore
 */
exports._PRELOADING = _PRELOADING = false;

/**
 * Load image and return it on a Surface.
 *
 * **Note**
 *
 * All images must be preloaded like this:
 *
 *     $r.preload(["./images/ship.png", "./images/sunflower.png"]);
 *
 * and can then be used inside the $r.ready() callback function
 * by bying loaded like this (path loses leading slash):
 *
 *     var ship = gamejs.image.load("images/ship.png");
 *
 * @param {String|dom.Image} uriOrImage ressource uri for image or the image as Dom Element (e.g. from <img>)
 * @returns {gamejs.Surface} surface with the image on it.
 */
exports.load = function(uriOrImage) {
   var img;
   if (typeof uriOrImage === 'string') {
      img = CACHE[uriOrImage];
      if (!img) {
         // FIXME sync image loading
			gamejs.log('[image] not in cache ' + uriOrImage);
			throw new Error('could not load image');
      }
   } else {
      img = uriOrImage;
   }
   var canvas = document.createElement('canvas');
   canvas.width = img.naturalWidth;
   canvas.height = img.naturalHeight;
   var context = canvas.getContext('2d');
   //context.fillStyle = "#00ff00";
   //context.fillRect(0, 0, canvas.width, canvas.height);
   context.drawImage(img, 0, 0)
   img.getSize = function() { return [img.naturalWidth, img.naturalHeight]; };
   var surface = new gamejs.Surface(img.getSize());
   // NOTE hack setting _canvas directly, don't do this yourself
   surface._canvas = canvas;
   return surface;
};
   
   
/**
 * add all images on the currrent page into cache
 * @ignore
 */
exports.init = function() {
   var imgs = Array.prototype.slice.call(document.getElementsByTagName("img"), 0);
   addToCache(imgs);
   return;
};

/**
 * preload the given img URIs
 * @ignore
 */
exports.preload = function(imgUrls) {
   if (!imgUrls.length) return;
   
   var countLoaded = 0;
   _PRELOADING = true;
   
   var incrementLoaded = function() {
      countLoaded++;
      if (countLoaded == imgUrls.length) {
         _PRELOADING = false;
      }
   };
   
   for(var i=0; i<imgUrls.length; i++) {
      var img = new Image();
      img.addEventListener('load',function() {
         addToCache(this);
         incrementLoaded();
         return;
      }, true);
      img.addEventListener('error', function() {
      	gamejs.log('[image] failed to load ' + this.src);
         incrementLoaded();
         return;
      }, true);
      img.src = imgUrls[i];
   }
   return;
};

/**
 * add the given <img> dom elements into the cache.
 * @private
 */
var addToCache = function(imgs) {
   if (!(imgs instanceof Array)) imgs = [imgs];
   
   var docLoc = document.location.href;
   imgs.forEach(function(img) {
      var key = img.src;
      if (key.slice(0, docLoc.length) === docLoc) {
         key = key.slice(docLoc.length);
      }
      CACHE[key] = img;
      gamejs.log('[image] added ' + key + ' to cache'); 
   });
   return;
};
